package Servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLStreamException;

import org.apache.solr.client.solrj.SolrServerException;

import DataObjects.Article;
import SolR.MySolR;
import XMLCreator.XMLCreatorArticle;

public class ArticleResultServlet extends SuperServlet {

	private static final long serialVersionUID = 1L;

	private MySolR solR;

	public ArticleResultServlet(MySolR solR){
		this.solR=solR;
	}

	protected String[] fieldThatMustBe(){
		String[] ans={"id"}; 
		return ans;
	}


	protected void buildResponse(HttpServletRequest request, HttpServletResponse response) throws IOException {
		int id=fieldToInt(request, "id",-1);
		if (id!=-1){
			try {
				LinkedList<Article> articles = solR.query("id:"+id,0).getSecend();//TODO not need solR
				//System.out.println();id
				if (articles.size()==1){
					PrintWriter out=response.getWriter();
					try {
						new XMLCreatorArticle().build(articles.getFirst(), out);
//						new XML3().build(null, out);
					} catch (XMLStreamException e) {
						System.out.println("Error 7 ArticleResultServlet");//TODO error 7 ArticleResultServlet
					} catch (FactoryConfigurationError e) {
						System.out.println("Error 8 ArticleResultServlet"); //TODO Error 8 ArticleResultServlet
					}
					out.close();
				}
				else
					System.out.println("Error 11 no article ArticleResultServlet");//TODO Error 11 ArticleResultServlet
			} 	
			catch (SolrServerException e1) {
				System.out.println("Error 10 ArticleResultServlet");//TODO Error 10 ArticleResultServlet
			}
		}//end if
		else{
			System.out.println("Error 6 ArticleResultServlet");//TODO Error 6 ArticleResultServlet
		}
	}

}
